<?php
/**
 * 验证码帮助类.
 *
 * @author linqiangy <linqiangy@kuainiugroup.com>
 */

namespace common\util;

/**
 * Class MessageCode.
 */
class MessageCode
{
    /**
     * 验证码缓存Key.
     *
     * @var string
     */
    public static $codeCacheKey = "code_cache_";

    /**
     * 生成随机验证码.
     *
     * @return integer
     */
    public function genRandMessageCode()
    {
        // 生成随机验证码.
        return rand(111111, 999999);
    }

    /**
     * 生成验证码.
     *
     * @param integer $mobile 手机号.
     *
     * @return mixed
     * @throws \Exception
     */
    public function genMessageCode($mobile)
    {
        $code = $this->genRandMessageCode();
        $key  = $this->getMessageCacheKey($mobile);

        // 验证码15分钟内有效.
        if (!\Yii::$app->cache->set($key, $code, 15 * 60)) {
            throw new \Exception("生成验证码失败");
        }
        return $code;
    }

    /**
     * 生成验证码缓存Key.
     *
     * @param $mobile
     *
     * @return string
     */
    public function getMessageCacheKey($mobile)
    {
        return self::$codeCacheKey . $mobile;
    }

    /**
     * 获取手机号验证码.
     *
     * @param integer $mobile 手机号.
     *
     * @return mixed
     */
    public function getMessageCodeByMobile($mobile)
    {
        $key   = $this->getMessageCacheKey($mobile);
        $cache = \Yii::$app->cache;

        return $cache->get($key);
    }

    /**
     * 校验用户手机验证码.
     *
     * @param integer $mobile      手机号.
     * @param integer $messageCode 手机验证码.
     *
     * @return boolean
     */
    public function validateMessageCodeByMobile($mobile, $messageCode)
    {
        $key   = $this->getMessageCacheKey($mobile);
        $cache = \Yii::$app->cache;
        $code  = $cache->get($key);

        if ($code && $code == $messageCode) {
            return true;
        }

        return false;
    }

}
